package org.example.exampreparationtreasure.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {

    /**
     * 生成盐值
     * @return 随机盐值
     */
    public static String generateSalt() {
        Random random = new Random();
        StringBuilder salt = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            salt.append(random.nextInt(10));
        }
        return salt.toString();
    }

    /**
     * @param str  需要加密的字符串
     * @param salt
     * @return 加密后的字符串
     */
    public static String encrypt(String str, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] bytes = md.digest(str.getBytes());

            StringBuilder result = new StringBuilder();
            for(byte b : bytes)
            {
                String hex = Integer.toHexString(b & 0xff);
                if(hex.length() == 1)
                {
                    result.append("0");
                }
                result.append(hex);
            }
            return result.toString();
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new RuntimeException("加密失败",e);
        }
    }

    /**
     * 验证密码
     * @param password 原始密码
     * @param salt 盐值
     * @param encryptedPassword 加密后的密码
     * @return 是否匹配
     */
    public static boolean verify(String password, String salt, String encryptedPassword) {
        return encrypt(password, salt).equals(encryptedPassword);
    }
}
